package com.pcbly.web.components.utils.fileupload.listener;

import org.apache.commons.fileupload.ProgressListener;
import org.apache.log4j.Logger;

import com.pcbly.web.components.utils.fileupload.UploadSessionImpl;
import com.pcbly.web.components.utils.fileupload.UploadSessionManager;

/**
 * This is a File Upload Listener that is used by Apache Commons File Upload to
 * monitor the progress of the uploaded file.
 * 
 * @author Frank T. Rios
 * 
 *         Initial Creation Date: 6/24/2007
 */
public class FileUploadListener implements ProgressListener {
	private volatile long bytesRead = 0L, contentLength = 0L, item = 0L;
	private static final Logger logger = Logger.getLogger(FileUploadListener.class);
	private String uSessionId=null;
	public FileUploadListener() {
		super();
	}
	public FileUploadListener(String uSessionId){
		this.uSessionId=uSessionId;
	}
	/**
	 * 更新状态,每读取50K更新一次
	 * @param pBytesRead 读取字节总数
	 * @param pContentLength 数据总长度
	 * @param pItems 当前正在被读取的field号
	 */
	public void update(long pBytesRead, long pContentLength, int pItems){
		if (bytesRead==0){
			bytesRead=pBytesRead;
		}
		UploadSessionImpl uSession=UploadSessionManager.getInstance().getUploadSession(this.uSessionId);
		//传输没有被取消或者出现错误
		if (!uSession.getActiveFUSBean().getCancel() && uSession.getActiveFUSBean().getStatus().indexOf("错误")<0){
			uSession.getActiveFUSBean().setProcessRunningTime(System.currentTimeMillis()-uSession.getActiveFUSBean().getProcessStartTime());
			
			//读取增加量超过50K或者读取结束
			if ((pBytesRead-bytesRead)>10240 || pContentLength==-1){
				logger.debug("更新文件上传会话["+uSession.getId()+"]");
		//		logger.debug("当前正在处理第" + pItems+"部分");
				uSession.getActiveFUSBean().setUploadTotalSize(pContentLength);
				uSession.getActiveFUSBean().setReadTotalSize(pBytesRead);
				//读取完成
			    if (pContentLength == -1) {
		//	    	logger.debug("读取完成:读取了 " + pBytesRead + " bytes.");
			    	uSession.getActiveFUSBean().setStatus("完成对" + pItems+"部分的读取:读取了 " + 
			    			uSession.getActiveFUSBean().getReadTotalSize() + " bytes.");
			    //读取中
			    } else {
		//	    	logger.debug("读取进行中:已经读取了 " + pBytesRead + " / " + pContentLength+ " bytes.");
			    	uSession.getActiveFUSBean().setStatus("当前正在处理第" + pItems+"部分:已经读取了 " + 
			    			uSession.getActiveFUSBean().getReadTotalSize() + " / " + 
			    			uSession.getActiveFUSBean().getUploadTotalSize()+ " bytes.");
			    }
			    bytesRead=pBytesRead;
			}
		}
		else{
			uSession.getActiveFUSBean().setStatus("正在进行取消处理...");
		}
		UploadSessionManager.getInstance().addOrUpdateUploadSession(uSession);
	}

	public long getBytesRead() {
		return bytesRead;
	}

	public long getContentLength() {
		return contentLength;
	}

	public long getItem() {
		return item;
	}
}
